const express = require('express');
const path = require('path');
const fs = require('fs');
const cors = require('cors');
const http = require('http');
const bookmarkRoutes = require('./src/routes/bookmark');
const technicalVision = require('./src/routes/technicalVision');
const interviewQ = require('./src/routes/interviewQ');
const interviewQCategories = require('./src/routes/interviewQCategories');

const app = express();
app.use(cors());
app.use(express.json());

// const options = {
//   key: fs.readFileSync('./httpsCcie/key.pem'), // 替换为你的密钥文件路径
//   cert: fs.readFileSync('./httpsCcie/cert.pem'), // 替换为你的证书文件路径
// };

// 读取目录结构的函数
function readDirectory(dirPath) {
  const buildTree = (dirPath) => {
    try {
      const files = fs.readdirSync(dirPath);
      let tree = [];

      files.forEach((file) => {
        const filePath = path.join(dirPath, file);
        const stats = fs.statSync(filePath);

        if (stats.isDirectory()) {
          tree.push({
            name: file,
            type: 'directory',
            children: buildTree(filePath), // 递归读取子目录
          });
        } else {
          tree.push({
            name: file,
            type: 'file',
          });
        }
      });

      return tree;
    } catch (error) {
      console.error(`Error reading directory: ${error}`);
      return null;
    }
  };
  const tree = buildTree(dirPath);
  if (tree) {
    return { name: path.basename(dirPath), children: tree };
  } else {
    return null;
  }
}

// 新增的路由，返回目录树
app.get('/directoryTree', (req, res) => {
  console.log('🚀 ~ app.get ~ req:', req.query);
  const dirPath = req.query.directory; // 指定你想要读取的目录路径
  console.log('🚀 ~ app.get ~ dirPath:', dirPath);
  const tree = readDirectory(dirPath);
  if (tree !== null) {
    res.json(tree);
  } else {
    res.status(500).send('Failed to retrieve directory tree.');
  }
});

app.use('/api/bookmarks', bookmarkRoutes);
app.use('/api/technicalVision', technicalVision);
app.use('/api/interviewQ', interviewQ);
app.use('/api/interviewQCategories', interviewQCategories);

// 启动HTTPS服务器
const server = http.createServer(app);
const PORT = 8000;
server.listen(PORT, () => {
  console.log(`HTTPS server running on port ${PORT}`);
});
